package bysj.controller.basic;

import bysj.domain.User;
import bysj.domain.authority.Actor;
import bysj.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login.ctl")
public class LoginController extends HttpServlet {
    /**
     * GET, http://localhost:8080/actor.ctl?id=1, 查询id=1的学院
     * GET, http://localhost:8080/actor.ctl, 查询所有的学院
     * 把一个或所有学院对象响应到前端
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String user_json = JSONUtil.getJSON(request);
        //将JSON字串解析为User对象
        User userToLogin = JSON.parseObject(user_json, User.class);
        System.out.println(userToLogin);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();

        try {
            Actor currentActor = UserService.getInstance().login(userToLogin,message);
            System.out.println(currentActor);
            if (currentActor == null) {
                message.put("message", "用户名或密码不匹配");
                response.getWriter().println(message);
                return;
            } else {
                message.put("actor", currentActor);
                //输出JSON字串时，屏蔽某些字段
                SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
                //不输出"department"、"title"和"degree"
                filter.getExcludes().add("department");
                filter.getExcludes().add("title");
                filter.getExcludes().add("degree");
                response.getWriter().println(JSON.toJSONString(message,filter));
            }
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            //响应message到前端
            response.getWriter().println(message);
            e.printStackTrace();
        } catch (Exception e) {
            message.put("message", "网络异常");
            //响应message到前端
            response.getWriter().println(message);
        }
    }

}
